package com.guli.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.edu.entity.Chapter;
import com.guli.edu.entity.Video;
import com.guli.edu.mapper.ChapterMapper;
import com.guli.edu.service.ChapterService;
import com.guli.edu.service.VideoService;
import com.guli.edu.vo.ChapterVo;
import com.guli.edu.vo.VideoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author jiangli
 * @since 2019-11-28
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

	@Autowired
	private VideoService videoService;

	@Override
	public void removeChapterById(String id) {

		//根据章节id删除所有视频
		videoService.removeById(id);

		//根据章节id删除章节
		baseMapper.deleteById(id);
	}

	@Override
	public List<ChapterVo> nestedList(String courseId) {
		//前端需要的数据列表
		List<ChapterVo> chapterVos = new ArrayList<>();

		//获取章节信息
		QueryWrapper<Chapter> queryWrapperChapter = new QueryWrapper<>();
		queryWrapperChapter.eq("course_id", courseId);
		queryWrapperChapter.orderByAsc("sort", "id");
		List<Chapter> chapters = baseMapper.selectList(queryWrapperChapter);

		//获取课时信息
		QueryWrapper<Video> queryWrapperVideo = new QueryWrapper<>();
		queryWrapperVideo.eq("course_id", courseId);
		queryWrapperVideo.orderByAsc("sort", "id");
		List<Video> videos = videoService.list(queryWrapperVideo);

/*		chapterVos = chapters.stream().map(e->{
			//创建章节vo对象
			ChapterVo chapterVo = new ChapterVo();
			BeanUtils.copyProperties(e, chapterVo);

			List<VideoVo> videoVos = videos.stream().map(v->{
				VideoVo videoVo = new VideoVo();
				if (v.getChapterId().equals(e.getId())) {
					BeanUtils.copyProperties(v,videoVo);
				}
				return videoVo;
			}).collect(Collectors.toList());

			chapterVo.setChildren(videoVos);
			return chapterVo;
		}).collect(Collectors.toList());*/

		//填充章节vo数据
		for (Chapter chapter : chapters) {
			//创建章节vo对象
			ChapterVo chapterVo = new ChapterVo();
			BeanUtils.copyProperties(chapter, chapterVo);

			//填充视频vo数据
			ArrayList<VideoVo> videoVoArrayList = new ArrayList<>();
			for (Video video : videos) {

				if (chapter.getId().equals(video.getChapterId())) {

					//创建视频vo对象
					VideoVo videoVo = new VideoVo();
					BeanUtils.copyProperties(video, videoVo);
					videoVoArrayList.add(videoVo);
				}
			}
			chapterVo.setChildren(videoVoArrayList);
			chapterVos.add(chapterVo);
		}
		return chapterVos;
	}
}
